package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.*;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BaseException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private IStatementService statementService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        // 设置 创建时间
        carPackageAudit.setCreateTime(new Date());
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    public void updateProcessInstanceId(Long id, String processInstanceId) {
        carPackageAuditMapper.updateProcessInstanceId(id, processInstanceId);
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = this.get(id);
        BpmnInfo bpmnInfo = bpmnInfoService.get(carPackageAudit.getBpmnInfoId());
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        InputStream inputStream=null;
        //如果状态为审核中或者审核拒绝，说明还正在流程中
        if(carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS) ){
            Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

            inputStream = generator.generateDiagram(model, activeActivityIds, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }else{
            //
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }

        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        /**
             //审核撤销前提： 只有在审核中才可以操作
             // 套餐服务单项状态：初始化
             // 审核记录数据状态：审核撤销
             // activiti 流程停止
         */
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 审核撤销前提： 只有在审核中才可以操作
        if (audit == null || audit.getStatus() != CarPackageAudit.STATUS_IN_ROGRESS){
            throw new BaseException("审核状态中不能撤销");
        }
        //套餐服务单项状态：初始化
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);

        //审核记录数据状态：审核撤销
        carPackageAuditMapper.changeStatus(id, CarPackageAudit.STATUS_CANCEL);

        // activiti 流程停止(删除流程实例)
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "审核撤销");

    }

    @Override
    public void audit(Long id, int auditStatus, String info) {
        // 审核三段论：审核条件 + 审核通过 + 审核不通过

        // 审核的参与方： 审核套餐（ServiceItem）、 审核记录信息（CarPackageAudit）、activiti流程（审核结束最近会删除）
        CarPackageAudit audit = carPackageAuditMapper.selectByPrimaryKey(id);
        // 1 审核条件 ： 审核中
        if (audit == null || !audit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)){
            throw new BaseException("只有在审核状态才能进行审核");
        }
        // 处理审核记录信息（CarPackageAudit） --- 具体的审核信息
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            // 通过
            audit.setAuditRecord(audit.getAuditRecord() +"<br>"+ userName+"【同意】,批注意见:"+info);
        }else{
            // 拒绝
            audit.setAuditRecord(audit.getAuditRecord() +"<br>"+ userName+"【拒绝】,批注意见:"+info);
        }
        // ******** 核心点1： *********
        // 推动流程 -- 执行处理当前节点
        Task currentTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();
        // 设置审核状态，让排他网关决定 -- 通过/拒绝 流程
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        // activiti 备注表中记录审核备注
        taskService.addComment(currentTask.getId(),audit.getInstanceId(),info);
        // 处理节点（处理任务节点） -- 推动流程
        taskService.complete(currentTask.getId());


        //获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId()).singleResult();

        // 思考：
        // 2 审核通过--做啥  -->  设计2条分支
        if (auditStatus == CarPackageAudit.STATUS_PASS){
            // 店长审核通过---并且价格大于3000  --- 走财务审核 ---- 状态不会变动
            // 财务审核通过 ---流程结束 ----状态都会变
            // 怎么知道当前是店长审核还是财务审核？ ---》 处理完单前节点，马上获取下一个节点
            // 2.1 获取下一个节点，判断该节点是否为 null
            if (nextTask == null){
                //   如果为 null ，当前流程结束  -->
                //   服务套餐（serviceItem）状态改为审核通过，审核记录信息（CarPackageAudit）状态改为审核通过
                serviceItemService.updateAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                audit.setStatus(CarPackageAudit.STATUS_PASS);
            }else {
                //   如果下一个节点不为 null 表示当前节点为店长审核，下一个节点时财务审核：当期审核流程没有完成，所有对象状态不需要改动，还是审核中
                //   审核记录信息（CarPackageAudit）： 当前审人为财务审核负责人 + 当前审核时间 new Date（）
                // 财务审核
                System.out.println(nextTask.getAssignee());
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }

        }else {
            // 3审核不通过 --> 做啥：
            // 3.1)服务套餐改为初始化，
            serviceItemService.updateAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
            // 3.2)审核记录信息状态改为：拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);

        }
        // 设置审核时间
        audit.setAuditTime(new Date());
        //  跟新审核信息
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
